FEZX.Comment = {};

FEZX.Comment.Util = {
	/**
	 * 文字列の横幅を返す
	 * @param str
	 * @returns
	 */
	getStrWidth : function(str){
		len = 0;
		str = escape(str);
		for ( var i = 0; i < str.length; i++, len++) {
			if (str.charAt(i) == "%") {
				if (str.charAt(++i) == "u") {
					i += 3;
					len++;
				}
				i++;
			}
		}

		return len;
	},

	splitStrLength : function (str, length){
		str1 = "", str2 = "";

		len = 0;

		addStr = function(char){
			if(len > length){
				str2 += char;
			}
			else{
				str1 += char;
			}
		};

		str = escape(str);
		for (var i = 0; i < str.length; i++, len++) {
			if (str.charAt(i) == "%") {
				if (str.charAt(i+1) == "u") {
					len++;

					addStr(str.charAt(i));
					i++;
					addStr(str.charAt(i));
					i++;
					addStr(str.charAt(i));
					i++;
				}

				addStr(str.charAt(i));
				i++;
				addStr(str.charAt(i));
				i++;
			}
			addStr(str.charAt(i));
		}
		str1 = unescape(str1);
		str2 = unescape(str2);

		return [str1 , str2];
	},

	showMessage : function(msg, isError){
		$('#ul_error_msg').hide();
		$("#ul_standard_msg").hide();
		
		if(isError){
			$('#ul_error_msg').html('<li>' + msg + '</li>');
			(function(){
				$("#ul_error_msg").slideDown("slow").click(function(){
					$('#ul_error_msg').slideUp('slow');
				});
			})();
		}
		else{
			$('#ul_standard_msg').html('<li>' + msg + '</li>');
			(function(){
				$("#ul_standard_msg").slideDown("slow").click(function(){
					$('#ul_standard_msg').slideUp('slow');
				});
			})();
		}
	},

	optimizeLine : function(str){
		str = str.replace("  ", "　");

		return str;
	},

	optimizeShowLine : function(str){
		str = str.replace("<hp>", "1000");
		str = str.replace("<pw>", "100");
		str = str.replace("<pos>", "[A:1]");
		str = str.replace("<cry>", "50");

		return str;
	},
	
	changeTextArea : function(selector, height, width){
		var target = $(selector);
		
		if(isFinite(height)){
			target.attr("rows", height);
		}
		
		if(isFinite(width)){
			target.attr("cols", width);
		}
	},

	dummy : null
};

FEZX.Comment.Object = function(){
	this._init();
};

FEZX.Comment.Object.prototype = {

	_changeChatColor : function(){
		var range="";
		$('.range').each(function(){
			if($(this).attr('checked')){
				range = $(this).attr('value');
			}
		});
		
		
		if(range == "p"){
			$("#result_chat").css("color", "#01FFFF");
			return;
		}
		
		if(range == "a"){
			$("#result_chat").css("color", "#FFFF00");
			return;
		}
		
		if(range == "f"){
			$("#result_chat").css("color", "#02FB00");
			return;
		}
		
		if(range == "as"){
			$("#result_chat").css("color", "#FFBC5D");
			return;
		}
		
		$("#result_chat").css("color", "#FFFFFF");
		return;
	},
		
	_init : function(){

		var self = this;
		var disable = function(){
			$('#comment').attr('disabled', 'disabled');

			$('.type').each(function(){
				$(this).attr('disabled', 'disabled');
			});

			$('.range').each(function(){
				$(this).attr('disabled', 'disabled');
			});

			$('#result_line').attr('value', '');
			$('#result_line').attr('disabled', 'disabled');

			$('#result_chat').html('');
			$('#result_balloon').html('');
			$('#result_balloon').hide();

		};

		var enable = function(){
			var str = $('#name').attr('value');
			var width = FEZX.Comment.Util.getStrWidth(str);

			if(width < FEZX.Const.Comment.CHARNAME_MIN_LENGTH){
				return;
			}

			if(width > FEZX.Const.Comment.CHARNAME_MAX_LENGTH){
				return FEZX.Comment.Util.showMessage('キャラクターの最大文字数オーバー', true);
			}

			var remain = FEZX.Const.Comment.WIDTH_LENGTH - width;
			FEZX.Comment.Util.showMessage('横幅残り：半角' + remain + '字分（改行コード除く:半角' + (remain - 5) + '字分）');

			$('#comment').removeAttr('disabled');

			// 未実装の為コメントアウト
			//$('.type').each(function(){
			//	$(this).removeAttr('disabled');
			//});

			$('.range').each(function(){
				$(this).removeAttr('disabled');
			});

			$('#result_line').removeAttr('disabled');

			self._calcResult(self);
		};

		$('#name').focus(disable).blur(enable);
		$('#debug').click(function(){
			self._calcResult(self);
		});

		$('#comment').keyup(function(){
			self._calcResult(self);
		});

		$('.range').change(function(){
			self._calcResult(self);
		});

		$('.type').change(function(){
			self._calcResult(self);
		});

		disable();
		enable();
	},

	_calcResult : function(self){
		var range="";
		
		self._changeChatColor();
		
		$('.range').each(function(){
			if($(this).attr('checked')){
				range = $(this).attr('value');
			}
		});

		var addStr = "";
		if(range.length){
			addStr = "/" + range + " ";
		}

		var str = "";
		var comment = $('#comment').attr('value');
		comment = comment.replace(/\r\n/g, "\n");
		/**
		// 未実装の為コメントアウト
		var type = "1";

		$('.type').each(function(){
			if($(this).attr('checked')){
				type = $(this).attr('value');
			}
		});
		*/

		var lines = comment.split("\n");

		// タイプを増やした場合ここで分岐
		for(var i in lines){
			str += FEZX.Comment.Util.optimizeLine(lines[i]);
			if(i != (lines.length - 1)){
				str += '<br/>';
			}
		}

		// 命令文と本文を結合した場合の文字数の確認（長すぎる場合は本文をカット）
		var strs = FEZX.Comment.Util.splitStrLength(addStr + str , FEZX.Const.Comment.STR_MAX_LENGTH );

		if(strs[1].length){
			$('#length_err').html('<li>半角' + FEZX.Comment.Util.getStrWidth(strs[1]) + '字分オーバーしています。</li>');
			$('#length_err').show();
		}
		else{
			$('#length_err').hide();
		}

		var optimize = strs[0];
		str = optimize.replace(addStr, "");

		$('#result_line').attr('value', addStr + str);
		self._showChat(str);
		self._showBallon(str);
	},

	_showChat : function(result){
		var name = $('#name').attr('value') + ':';

		var str = name;

		var nameLength = FEZX.Comment.Util.getStrWidth(str);

		var remain = FEZX.Const.Comment.WIDTH_LENGTH - nameLength;


		var text = "";
		var lineNumber = 1;
		result = FEZX.Comment.Util.optimizeShowLine(result);
		while(true){
			var array = FEZX.Comment.Util.splitStrLength(result, remain);

			text += str + array[0];
			str = " ";
			
			if(array[1].length == 0){
				break;
			}
			
			for(var i=1 ; i < nameLength ; i++){
				str += " ";
			}
			
			text += "\n";
			lineNumber++;

			result = array[1];
		}
		
		var userAgent = window.navigator.userAgent.toLowerCase();
		if (userAgent.indexOf('msie') != -1) {
			text = text.replace("\n", "\r\n");
		}

		
		FEZX.Comment.Util.changeTextArea('#result_chat', lineNumber);
		$('#result_chat').val(text);
	},

	_showBallon : function(result){
		/**
		 * <br/>タグを使った場合、デッドコメントの横幅制限は半角40文字です。
		 * <br/>タグまでの一行の長さが半角40文字を超えていた場合、
		 * 強制的に改行されます。
		 */
		$('#result_balloon').hide();
		
		if(result.length){
			$('#result_balloon').show();
		}
		
		text = "";
		var lines = FEZX.Comment.Util.optimizeShowLine(result).split('<br/>');
		var maxwidth = 0;
		var lineNumber = 0;
		for(var i in lines){
			var line = lines[i];

			while(true){
				var array = FEZX.Comment.Util.splitStrLength(line, FEZX.Const.Comment.BALLON_LINE_LENGTH);

				var lineFix = array[0] + "\n";
				text += lineFix;
				lineNumber++;
				if(maxwidth < FEZX.Comment.Util.getStrWidth(lineFix)){
					maxwidth = FEZX.Comment.Util.getStrWidth(lineFix);
				}

				if(array[1].length == 0){
					break;
				}

				line = array[1];
			}
		}
		
		FEZX.Comment.Util.changeTextArea('#result_balloon', lineNumber, maxwidth-1);
		$('#result_balloon').val(text);
	},

	dummy: null
};

$(function(){
	new FEZX.Comment.Object();
	
	// FAQ
	$("#button_faq_show").click(function(){
		$("#div_faq").show("fast");
	});
	
	$("#button_faq_hide").click(function(){
		$("#div_faq").hide("fast");
	});
});